package cn.forward.template;

import cn.forward.properties.AppUrlProperties;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;


public class WechatTemplate {

    private AppUrlProperties appUrlProperties;

    public WechatTemplate(AppUrlProperties appUrlProperties) {
        this.appUrlProperties = appUrlProperties;
    }


    /**
     * 通过code获取openid
     *
     * @param openIdCod
     * @param
     */
    public String openIdByCode(String openIdCod) {


        String CodeToOpenidUrl = appUrlProperties.getCodeToOpenidUrl();

        String formatted = String.format(CodeToOpenidUrl, appUrlProperties.getAppId(), appUrlProperties.getAppSecret(), openIdCod);
        String result = HttpUtil.get(formatted);
        JSONObject OpenIdObject = JSONUtil.parseObj(result);
        String openid = OpenIdObject.getStr("openid");
        if (StrUtil.isBlank(openid)) {
            throw new RuntimeException("参数异常");
        }

        return openid;

    }


    /**
     * 通过appID和secret获取access
     *
     * @return
     */

    public String ToAccessToken() {

        String accessUrl = appUrlProperties.getAapAccessUrl();

        String accessFormat = String.format(accessUrl, appUrlProperties.getAppId(), appUrlProperties.getAppSecret());
        String accessResult = HttpUtil.get(accessFormat);
        JSONObject jsonResult = JSONUtil.toBean(accessResult, JSONObject.class);
        String accessToken = jsonResult.getStr("access_token");
        if (StrUtil.isBlank(accessToken)) {
            throw new RuntimeException("获取accessToken参数异常");
        }

        return accessToken;


    }


    /**
     * 通过phoneCode和access获取电话
     *
     * @param
     * @return
     */
    public String phoneByCode(String phoneCod) {

        String phoneUrl = appUrlProperties.getCodeAccessToPoneUrl();

        String access = ToAccessToken();

        String phoneResult = String.format(phoneUrl, access);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", phoneCod);
        String resultPhoneStr = HttpUtil.post(phoneResult, jsonObject.toString());
        JSONObject resultPhoneObj = JSONUtil.parseObj(resultPhoneStr);
        Integer errCode = resultPhoneObj.getInt("errcode");
        if (0 != errCode) {
            throw new RuntimeException("获取手机号失败");
        }
        JSONObject jsonObjectPhone = resultPhoneObj.getJSONObject("phone_info");
        String phoneNumber = jsonObjectPhone.getStr("phoneNumber");

        if (StrUtil.isBlank(phoneNumber)) {
            throw new RuntimeException("获取手机号失败");
        }

        return phoneNumber;

    }




}
